package middleware

import (
	"net/http"
	"strings"

	"gitee.com/chuanjinge/gopkgserv/pkg/auth"
	"github.com/gin-gonic/gin"
)

// AuthMiddleware 校验JWT token并将userId注入上下文
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "缺少token"})
			c.Abort()
			return
		}
		token = strings.TrimPrefix(token, "Bearer ")
		claims, err := auth.ParseToken(token)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "token无效"})
			c.Abort()
			return
		}
		// 注入userId到上下文
		c.Set("userId", claims.UserID)
		c.Next()
	}
}
